package org.example.ecommerce_system.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.ecommerce_system.entity.Product;
import org.example.ecommerce_system.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
public class ProductController {
    @Autowired
    ProductMapper productMapper;

    //展示数据
    @RequestMapping("/getAllPro")
    public PageInfo<Product> getAll(@RequestParam(defaultValue = "1") int currentPage,
                                    @RequestParam(defaultValue = "5") int pageSize){
        try {
            PageHelper.startPage(currentPage, pageSize);
            List<Product> products = productMapper.getAll();
            return new PageInfo<>(products);
        } finally {
            PageHelper.clearPage(); // 确保清除分页设置
        }
    }
    //查询
    @RequestMapping("/searchPro")
    public PageInfo<Product> searchProduct(@RequestParam String proName, @RequestParam(defaultValue = "1") int currentPage,
                                           @RequestParam(defaultValue = "5") int pageSize){
        try {
            PageHelper.startPage(currentPage, pageSize);
            List<Product> products = productMapper.searchProduct(proName);
            return new PageInfo<>(products);
        } finally {
            PageHelper.clearPage();
        }
    }

    @RequestMapping("/searchPrice")
    public Map<String, Double> getPrice(String proName) {
        Map<String, Double> result = new HashMap<>();
        result.put("proPrice", productMapper.getPrice(proName));
        return result;
    }
    //删除
    @RequestMapping("/deletePro/{proID}")
    public int deleteProduct(@PathVariable int proID){
        return productMapper.deleteProduct(proID);
    }

    @RequestMapping("/insertPro")
    public int insertProduct(@RequestBody Product product){
        return productMapper.insertProduct(product);
    }

    @RequestMapping("/updatePro")
    public int updateProduct(@RequestBody Product product){
        return productMapper.updateProduct(product);
    }

    @RequestMapping("/findOne/{proID}")
    public Product getProductByID(@PathVariable int proID){
        return productMapper.getProductByID(proID);
    }

    @RequestMapping("/upload")
    public Map<String,String> uploadPhoto(@RequestParam("file") MultipartFile file) throws IOException {
        Map<String,String> result = new HashMap<>();
        if(!file.isEmpty()){
            byte[] bytes= file.getBytes();
            String base64 = Base64.getEncoder().encodeToString(bytes);
            result.put("imgPath",base64);
            result.put("status","success");
        }else {
            result.put("status","error");
            result.put("msg","文件为空");
        }
        return result;
    }

    // 【新增】库存回补接口
    @RequestMapping("/updateProductQuantity")
    public int updateProductQuantity(@RequestBody Map<String, Object> request) {
        String proName = (String) request.get("proName");
        Integer orderNumber = (Integer) request.get("number");
        // 1. 根据商品名称查询库存
        Product product = productMapper.getProductByName(proName);
        if (product == null) {
            return 0;
        }

        // 2. 计算新库存 = 原库存 + 订单数量
        // 添加非负校验
        int quantity = Math.max(0, product.getQuantity() + orderNumber);
// 打印日志（可选）
        System.out.println("库存更新：" + proName +
                " 原库存=" + product.getQuantity() +
                " 新库存=" + quantity);
        // 3. 执行库存更新
        return productMapper.updateQuantity(product.getProName(),quantity);
    }
}
